package com.five.author.service.Impl;

import com.five.Page.Page;
import com.five.Page.PageList;
import com.five.api.AuthorServiceAPI;
import com.five.author.mapper.AuthorMapper;
import com.five.author.service.AuthorService;
import com.five.dto.UpdateDto;
import com.five.exception.BusinessException;
import com.five.pojo.Author;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class AuthorServiceImpl implements AuthorService {

    @Autowired
    private AuthorMapper authorMapper;
    @Autowired
    private AuthorServiceAPI authorApi;

    @GlobalTransactional
    @Override
    public void insert(Author author) {
        if (author.getUsername() == null){
            throw new BusinessException("用户名不能为空");
        }
        if (author.getPassword() == null){
            throw new BusinessException("密码不能为空");
        }
        author.setCreateTime(new Date());
        authorMapper.insert(author);
    }
    @GlobalTransactional
    @Override
    public void deleteById(Long id) {
        if (id == null){
            throw new BusinessException("id不能为空");
        }
        authorMapper.deleteById(id);
    }

    @GlobalTransactional
    @Override
    public void updateById(Author author) {
        if (author.getId() == null){
            throw new BusinessException("id不能为空");
        }
        author.setUpdateTime(new Date());
        authorMapper.updateById(author);
    }

    @Override
    public Author selectById(Long id) {
        return authorMapper.selectById(id);
    }

    @Override
    public PageList<Author> selectByPage(Page<Author> page) {
        Integer totals = authorMapper.selectTotals();
        if (totals == null){
            return new PageList<>();
        }
        List<Author> authors = authorMapper.selectByPage(page);
        return new PageList<>(totals, authors);
    }

    @Override
    public List<Author> selectAll() {
        return authorMapper.selectAll();
    }

    @GlobalTransactional
    @Transactional
    @Override
    public void chapterAudit(List<Long> chapterIds) {
        for (Long chapterId : chapterIds) {
            UpdateDto updateDto = new UpdateDto();
            updateDto.setStatus((byte) 2);
            updateDto.setId(chapterId);
            authorApi.updateStatus(updateDto);
        }
    }
}
